<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
    <el-table style="margin: 10px 0" border :data="trademarkList">
      <el-table-column type="index" label="序号" width="100px" align="center" sortable></el-table-column>
      <el-table-column label="品牌名称" align="center" sortable>
        <template #="{row, $index}">
          <pre>{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌商标" align="center" sortable>
        <template #="{row, $index}">
          <img :src="row.logoUrl" :width="100" :height="70" alt="图片加载失败">
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" sortable>
        <template #="{row, $index}">
          <pre>{{ row.updateTime }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" sortable>
        <template #="{row, $index}">
          <el-button icon="Edit" type="text" @click="updateTrademark(row)"></el-button>
          <el-popconfirm :title="`确定删除${row.tmName}吗？`" width="200px" icon="Delete" @confirm="deleteTrademark(row.id)">
            <template #reference>
              <el-button icon="Delete" type="text" style="color: red"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="trademarkPageList"
        @size-change="trademarkPageList"
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="sizes, prev, pager, next, ->, jumper, total"
        :total="total"
    />
  </el-card>

  <!-- 新增对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="tradeMarParams.id ? '修改品牌' : '添加品牌'">
    <el-form
        ref="ruleFormRef"
        class="tradeMark_form"
        :model="tradeMarParams"
        :rules="rule"
        style="width: 90%">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input v-model="tradeMarParams.tmName"
                  type="text"
                  placeholder="请输入品牌名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="tradeMarParams.logoUrl" :src="tradeMarParams.logoUrl" style="width: 90%; height: 200px"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearButton">取消</el-button>
        <el-button type="primary" @click="confirmButton()">确认</el-button>
      </span>
    </template>
  </el-dialog>

</template>


<script setup lang="ts">
import {ref, onMounted, reactive, nextTick} from 'vue';
import {trademarkPage, trademarkAddOrUpdate, removeTrademark} from "@/api/product/trademark";

import type {
  Records,
  TradeMarkResponse,
  TradeMarkResp,
  TradeMark
} from "@/api/product/trademark/type";
import {ElNotification, ElMessage, UploadProps} from "element-plus";

// 当前页码
let pageNo = ref<number>(1);
// 每页展示数据条数
let pageSize = ref<number>(10);
// 总条数
let total = ref<number>(0);
// 品牌列表数据
let trademarkList = ref<Records>([]);
// 新增对话框
const dialogFormVisible = ref<boolean>(false)
let tradeMarParams = reactive<TradeMark>({tmName: '', logoUrl: ''})
let ruleFormRef = ref();


// 获取已有品牌的接口封装为一个函数，在任何情况下获取数据，调用次函数即可
const trademarkPageList = async () => {
  let result: TradeMarkResponse = await trademarkPage(pageNo.value, pageSize.value);
  if (result.code === 200) {
    total.value = result.data.total;
    trademarkList.value = result.data.records;
  } else {

  }
}


// 组件挂在完毕钩子--发一次请求， 获取第一页数据数据
onMounted(() => {
  trademarkPageList();
})

// 分页器当前页码发生变化的时候会除法，
// 对于当前页码发生变化自定义事件，组件Pagination父组件回传了数据（当前的页码）
// const changePageNo =()=>{
//   getHasTrademark();
// }

// 当下拉菜单发生变化的时候出发此方法
// 这个自定义事件，分页器组件会将下拉菜单选中数据返回
// const siezeChange = ()=>{
//   getHasTrademark();
// }

const addTrademark = () => {
  dialogFormVisible.value = true;
  tradeMarParams.id = undefined;
  tradeMarParams.tmName = '';
  tradeMarParams.logoUrl = '';

  nextTick(() => {
    ruleFormRef.value.clearValidate('tmName');
    ruleFormRef.value.clearValidate('logoUrl');
  })
}


const updateTrademark = (row: TradeMark) => {
  nextTick(() => {
    ruleFormRef.value.clearValidate('tmName');
    ruleFormRef.value.clearValidate('logoUrl');
  })
  dialogFormVisible.value = true;
  // ES6语法合并对象
  Object.assign(tradeMarParams, row);
  // tradeMarParams.id = row.id;
  // tradeMarParams.tmName = row.tmName;
  // tradeMarParams.logoUrl = row.logoUrl;

}


const deleteTrademark = async (id: number) => {
  let result: TradeMarkResp = await removeTrademark(id);
  if (result.code === 200) {
    ElMessage.success(result.message);
    await trademarkPageList();
  } else {
    ElMessage.error(result.message);
  }
}


const clearButton = () => {
  dialogFormVisible.value = false;
}


const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  tradeMarParams.logoUrl = response.data;
  // 图片上传成功，清除校验结果
  ruleFormRef.value.clearValidate('logoUrl');
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是jpg/jpeg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小必须在2MB以内!')
    return false
  }
  return true
}


const confirmButton = async () => {
  await ruleFormRef.value.validate();
  let result: TradeMarkResp = await trademarkAddOrUpdate(tradeMarParams);
  if (result.code === 200) {
    ElMessage.success(result.message);
    dialogFormVisible.value = false;
    pageNo.value = tradeMarParams.id ? pageNo.value : 1;
    await trademarkPageList();
    tradeMarParams.tmName = '';
    tradeMarParams.logoUrl = '';
  } else {
    ElMessage.error(result.message);
    tradeMarParams.tmName = '';
    tradeMarParams.logoUrl = '';
  }
}


const rule = ({
  tmName: [
    // {validator: validateUserName, trigger: 'change'}
    {required: true, message: '请输入品牌名称', trigger: 'blur'},
    {min: 3, max: 8, message: '账号长度在 3 到 8 个字符', trigger: 'blur'},
  ],
  logoUrl: [
    {required: true, message: '请上传品牌LOGO', trigger: 'blur'},
  ]
})


</script>


<style scoped>

</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>